package com.kelvem.saas.workbanch.fsm.container;

import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import com.kelvem.saas.workbanch.core.utils.BeanUtil;
import com.kelvem.saas.workbanch.fsm.core.FsmException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class DaoContainer {
    
    private static Map<Class<? extends Entity>, String> beanMap = new HashMap<>();
    private static Map<String, BaseDao> daoMap = new HashMap<>();
    
    public static BaseDao getDao(Class<? extends Entity> entityClazz) {
        // todo
        if (!beanMap.containsKey(entityClazz)) {
            String msg = String.format("Entity[%s]未找到对应的继承BaseDao的%s, 请检查",
                    entityClazz.getSimpleName(), entityClazz.getSimpleName().replaceAll("Entity", "Dao"));
            log.error(msg);
            throw new FsmException(msg);
        }
        
        String beanName = beanMap.get(entityClazz);
        return getDao(beanName);
    }
    
    public static BaseDao getDao(String beanName) {
        if (daoMap.containsKey(beanName)) {
            return daoMap.get(beanName);
        } else {
            BaseDao dao = BeanUtil.getBean(beanName);
            daoMap.put(beanName, dao);
            return dao;
        }
    }
    
    public static void addDao(Class<? extends Entity> entityClazz, String daoBeanName) {
        // todo
        beanMap.put(entityClazz, daoBeanName);
    
        BaseDao dao = BeanUtil.getBean(daoBeanName);
        daoMap.put(daoBeanName, dao);
    }
}
